<?php
/**********************************************************************//**\file
	Armory Update

	Description:  Pulls data from wowarmory.com, wowheroes.com, caches it, and
		updates the database.
*******************************************************************************/

	require_once('core/core.php');

	/*** WARNING ***
	 * Pulling data from wowarmory.com too frequently will result in your server
	 * being ip banned for at least 12 hours.  The network transfer class has
	 * been designed with a static few-second delay between requests to prevent
	 * network burst and reduce load on the queried servers.  Decay times for
	 * cached data have been set to reasonable defaults.  The script also
	 * automatically detects php's script execution time limitations and
	 * attempts to compensate as appropriate.
	 *
	 * Ultimately, the script will only pull fresh data if the current data is
	 * considered old, and will attempt to limit the rate of requests.
	 */

	# Initialize net transfer and database objects
	$fetch = new armorynet();
	$db = new armorydb();

	# Raw script rate limiter, prevents external abuse or runaway cron
	$db->query("SELECT runtime_value FROM armory_runtime WHERE runtime_name = 'last_run'");
	if($db->quick_result() > time() - 3500)
	{
		die('rate limited');
	}

	// date dump -> echo date('r', intval($db->quick_result()));

	# Collect data to prevent script timeout / limit net traffic
	$time_start = time();
	$time_limit = ini_get('max_execution_time') + $time_start;
	$total_requests = 0;

	# Update runtime
	$db->query("UPDATE armory_runtime SET runtime_value = '$time_start' WHERE runtime_name = 'last_run'");

	# Correct wowarmory domain prefix
	if($config['guild_region'] == 'us')
	{
		# If in the US, use the www prefix
		$wowtoken = 'www';
	}
	else
	{
		# Otherwise, use the local subdomain
		$wowtoken = $config['guild_region'];
	}

	# Wowarmory Guild Information
	$db->query("SELECT runtime_value FROM armory_runtime WHERE runtime_name = 'last_wowarmory'");
	if(intval($db->quick_result()) < time() - $constants['decay_time'])
	{
		# Initialize cache object
		$cache = new armorycache('guild');

		# Pull data from wowarmory
		if($data = $fetch->get('http://'.$wowtoken.'.wowarmory.com/guild-info.xml?r='.urlencode($config['guild_realm']).'&n='.urlencode($config['guild_name']).'&rhtml=n'))
		{
			# Store cache
			$cache->cache('wowarmory', $data);

			$db->query("UPDATE armory_runtime SET runtime_value = '".time()."' WHERE runtime_name = 'last_wowarmory'");
		}
		$total_requests++;

		# Parse fresh XML cache and update database
		$xml = new wowarmoryxml();
		$xml->parse();
		$xml->store();
	}
	
	# Wowheroes Guild Information
	$db->query("SELECT runtime_value FROM armory_runtime WHERE runtime_name = 'last_wowheroes'");
	if(intval($db->quick_result()) < time() - $constants['decay_time'])
	{
		# Initialize cache object
		$cache = new armorycache('guild');

		# Pull data from wowheroes
		if($data = $fetch->get('http://xml.wow-heroes.com/xml-guild.php?z='.$config['guild_region'].'&r='.urlencode($config['guild_realm']).'&g='.urlencode($config['guild_name']).'&rhtml=n'))
		{
			# Store cache
			$cache->cache('wowheroes', $data);

			$db->query("UPDATE armory_runtime SET runtime_value = '".time()."' WHERE runtime_name = 'last_wowheroes'");
		}
		$total_requests++;

		# Parse fresh XML cache and update database
		$xml = new wowheroesxml();
		$xml->parse();
		$xml->store();
	}

	# Wowarmory Player Information
	$decay_threshold = time()-$constants['decay_time'];
	$db->query("SELECT player_name, player_url FROM armory_player WHERE player_updated < $decay_threshold ORDER BY player_updated ASC LIMIT {$constants['batch_size']}");
	if($decayed_players = $db->multi_result())
	{
		$cache = new armorycache('player');

		foreach($decayed_players as $player)
		{
			# Pull data from wowarmory (Convert player_name to utf8 for players with extended characters)
			if($data = $fetch->get('http://'.$wowtoken.'.wowarmory.com/character-sheet.xml?'.$player['player_url'].'&rhtml=n'))
			{
				# Store cache
				$cache->cache($player['player_name'], $data);

				# Parse fresh XML cache and update database
				$xml = new playerxml($player['player_name']);
				$xml->parse();
				$xml->store();
			}

			$total_requests++;

			# Are we running out of time?
			if($time_limit - time() < 6 && ini_get('safe_mode'))
			{
				# Terminate request sequence
				break(2);
			}
			else
			{
				# Give us another 10 seconds to finish the rest of the batch
				set_time_limit(10);
			}
		}
	}
?>